package com.database.management.dao;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.database.management.base.BaseDao;
import com.database.management.db.DbPoolConnection;

public class IndexDao extends BaseDao{
	
	public IndexDao(Integer key) {
		super(key);
	}

	public Map execute(String sql) throws Exception{
		DruidPooledConnection connection = DbPoolConnection.getInstance().getConnection();
		Statement statement = connection.createStatement();
		boolean flag = statement.execute(sql);
		Map map = new HashMap();
		map.put("flag", flag);
		if(flag){
			ResultSet resultSet = statement.getResultSet();
			ResultSetMetaData md = resultSet.getMetaData();    
			map.put("columnList", displayMetaData(md));
            int columnCount = md.getColumnCount();
            List list = new ArrayList();
            while (resultSet.next()) {
                Map rowData = new HashMap();
                for (int i = 1; i <= columnCount; i++) {
                    rowData.put(md.getColumnName(i), resultSet.getObject(i));
                }
                list.add(rowData);
            }
			map.put("resultSet", list);
		
		}
		return map;
	}
	
	public List displayMetaData(ResultSetMetaData metaData) throws Exception { 
		List list = new ArrayList();
        for (int i = 0; i < metaData.getColumnCount(); i++) {  
        	Map map = new HashMap();
        	map.put("table",metaData.getTableName(i + 1));  
        	map.put("column",metaData.getColumnName(i + 1));  
        	map.put("type",metaData.getColumnType(i + 1));  
        	map.put("dbtype",metaData.getColumnTypeName(i + 1));  
        	map.put("size",metaData.getColumnDisplaySize(i + 1));  
        	list.add(map);
        }  
        return list;
    } 
	
}
